﻿#region Copyright
/// <copyright>
/// Copyright (c) 2008 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace Osh
{
	public class ServiceRegistry : IServiceRegistry
	{
		private Dictionary<Type, object> _services = new Dictionary<Type, object>();

		#region IServiceRegistry
		public virtual void RegisterService(object service)
		{
			if(service == null)
				throw new ArgumentNullException("service");
			RegisterService(service.GetType(), service);
		}

		public virtual void RegisterService(Type serviceType, object service)
		{
			if(service == null)
				throw new ArgumentNullException("service");
			_services[serviceType] = service;
		}

		public virtual void UnregisterService(Type serviceType)
		{
			if(_services.ContainsKey(serviceType))
				_services.Remove(serviceType);
		}

		public virtual T GetService<T>()
		{
			Type type = typeof(T);
			if(!_services.ContainsKey(type))
				return default(T);
			return (T)_services[type];
		}
		#endregion IServiceRegistry

		#region IScriptServiceProvider
		public virtual object GetService(string serviceType)
		{
			Type type = Type.GetType(serviceType, true);
			if(!_services.ContainsKey(type))
				return null;
			return _services[type];
		}
		#endregion IScriptServiceProvider

		#region IServiceProvider
		/// <remarks>
		/// ComVisible(false) attribute is used to avoid conflicts with GetService(string serviceType) method
		/// which otherwise will not be available from script.
		/// </remarks>
		/// <param name="serviceType"></param>
		/// <returns></returns>
		[ComVisible(false)]
		public object GetService(Type serviceType)
		{
			if(!_services.ContainsKey(serviceType))
				return null;
			return _services[serviceType];
		}
		#endregion IServiceProvider
	}
}
